<?php

namespace app\admin\controller;

use app\admin\middleware\CheckAdmin;
use app\BaseController;
use app\common\BusinessException;
use think\facade\Db;

class Permission extends BaseController
{
    protected $middleware = [
        CheckAdmin::class,
    ];

    public function index()
    {
        // 获取权限列表 分页
        $pageNum = $this->request->param('pageNum', 1);
        $pageSize = $this->request->param('pageSize', 10);

        $list = Db::name('permission')
            ->where('status', 1)
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $pageNum,
            ]);

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $list,
        ]);
    }

    public function create()
    {
        // 创建权限
        $name = $this->request->post('name');
        $path = $this->request->post('path');
        $status = $this->request->post('status');

        $result = Db::name('permission')->insert([
            'name' => $name,
            'path' => $path,
            'status' => $status,
        ]);

        if ($result) {
            $lastId = Db::name('permission')->getLastInsID();
        }

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $lastId,
        ]);
    }

    public function edit()
    {
        $data = $this->request->post();
        // 权限校验
        $id = $this->request->param('id');
        $permission = Db::name('permission')->where('id', $id)->find();

        if (!$permission) {
            throw new BusinessException('权限不存在');
        }

        // 更新权限
        $result = Db::name('permission')->where('id', $id)->update($data);

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $result,
        ]);

    }
}
